/**
*  @file
* @description 对axios进行二次封装
 */
import axios from 'axios'

import { Message } from "element-ui"
import store from "@/store"

axios.defaults.timeout = process.env.TIMEOUT
axios.defaults.baseURL = "/9yue"

/**
* 请求拦截器
 */
axios.interceptors.request.use(config => {
    config.headers.Authorization = store.getters.token;
    return config;
}, error => Promise.reject(error))

/**
*响应拦截器
*/
axios.interceptors.response.use(response => {
    const {
        data,
        meta: {
            status,
            msg
        }
    } = response.data
    if (status === 200 || status === 201) {
        return data
    }
    Message.error(msg)
    return Promise.reject(msg)
}, error => {
    const errorMsg = error.toString()
    if (errorMsg.includes('Network Error')) {
        Message.error('请求失败，请检查你的网络是否正常')
        return Promise.reject(error)
    }
    if (errorMsg.includes('Timeout')) {
        Message.error('请求超时，请稍后再试')
        return Promise.reject(error)
    }
    const { status } = error.response
    switch (status) {
        case 404:
            Message.error('接口不存在')
            break;
        case 500:
            Message.error('接口服务器请求失败，请稍后再试')
            break;
        case 401:
            Message.error('身份校验失败，请重新登录')
            break;

        default:
            Message.error('未知错误')
            break;
    }
    return Promise.reject(error)
})

export default axios